package czw.com.producer;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Component
public class TestProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //回调函数: confirm确认
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {

        @Override
        public void confirm(@Nullable CorrelationData correlationData, boolean ack, @Nullable String s) {
            System.err.println("correlationData: " + correlationData);
            String messageId = correlationData.getId();
            if(ack){
                //如果confirm返回成功 则进行更新
                System.out.println("czw----mq发送成功");
            } else {
                //失败则进行具体的后续操作:重试 或者补偿等手段
                System.err.println("czw------mq发送失败");
            }
        }
    };


    //发送消息方法调用: 构建自定义对象消息
    public void sendOrder() throws Exception {
        // 通过实现 ConfirmCallback 接口，消息发送到 Broker 后触发回调，确认消息是否到达 Broker 服务器，也就是只确认是否正确到达 Exchange 中
        rabbitTemplate.setConfirmCallback(confirmCallback);
        //消息唯一ID
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        String str="czw发送的消息---------------";
        rabbitTemplate.convertAndSend("czw-exchange", "czw.ABC", str, correlationData);
    }


}
